/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cc.gehua.octopus.rpc.utils;

import com.google.common.io.Resources;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author zzzhr
 */
public class ConfigUtil {

    private static final Logger log = LoggerFactory.getLogger(ConfigUtil.class);

    public static Map<String, Map<String, String>> readIniFile(String fileName) {
        URL resource;
        try {
            resource = Resources.getResource(fileName);
        } catch (Exception e) {
            log.error("Config file not found, exit.");
            return null;
        }

        if (null == resource) {
            log.error("Config file not found, exit.");
            return null;
        }
        IniEditor iniEditor = new IniEditor();
        try {
            iniEditor.load(new InputStreamReader(resource.openStream(), "UTF-8"));
        } catch (IOException ex) {
            log.error("Load config file error", ex);
            return null;
        }
        //Build Configs...
        Map<String, Map<String, String>> config = new HashMap<>();
        List<String> sectionNames = iniEditor.sectionNames();
        sectionNames.stream().forEach((section) -> {
            Map<String, String> mSection = config.get(section);
            if (mSection == null) {
                mSection = new HashMap<>();
                config.put(section, mSection);
            }
            List<String> optionNames = iniEditor.optionNames(section);
            for (String optionName : optionNames) {
                String option = iniEditor.get(section, optionName);
                mSection.put(optionName, option);
            }
        });
        return config;
    }
}
